import { ISingerDetailItem } from "@/fetch/type"
import { computed, onMounted, ref, Ref, watch } from "vue"

`
<audio ref="audioRef" class="audio" preload="metadata">
      <source src="./assets/朴树-平凡之路.mp3" type="audio/mp3">
    </audio>
`
const audioRef = ref<HTMLAudioElement>()
const currentLyric = ref('')
const currentSongList = ref<ISingerDetailItem[]>([])
const currentSongItem = ref<ISingerDetailItem>()
const currentIndex = ref(-1)
let endedTimer = null
let errorTimer = null
// 是否为循环播放
const isLoop = ref(true)
export const useAudio = () => {
  const baseUrl = import.meta.env.VITE_URL

  const isStop = ref(true)



  // 歌曲总时间---分钟
  const showTotalTime = computed(() => {
    let second = Math.floor(songTotleTime.value % 60) as any
    let minute = Math.floor(songTotleTime.value / 60) as any
    second = second < 10 ? '0' + second : second
    return minute + ':' + second
  })
  // 已经播放的时间---分钟
  const showNowTime = computed(() => {
    let second = Math.ceil(songNowTime.value % 60) as any
    let minute = Math.floor(songNowTime.value / 60) as any
    second = second < 10 ? '0' + second : second
    return minute + ':' + second
  })

  const songTotleTime = ref(0)
  const songNowTime = ref(0)

  let timer
  watch(audioRef, (ref) => {
    ref.addEventListener('pause', () => {
      console.log('音乐暂停了')
      isStop.value = true
      clearInterval(timer)
    })
    ref.addEventListener('play', () => {
      // console.log('音乐播放了')
      isStop.value = false
      // timer = setInterval(() => {
      //   songNowTime.value = getPlayTime()
      // }, 1000)
    })
    ref.addEventListener('ended', () => {
      isStop.value = true
      clearInterval(timer)
      if (endedTimer) return
      endedTimer = setTimeout(() => {
        if (isLoop.value) { //循环模式
          nextSong()
        } else { //随机模式
          const index = Math.floor(Math.random() * (currentSongList.value.length - 0)) + 0
          currentIndex.value = index
          changeSong(baseUrl + currentSongList.value[index].url)
        }
        endedTimer = null
      }, 100);


    })
    ref.addEventListener('loadeddata', () => {
      // 开始播放了
      isStop.value = false
      timer = setInterval(() => {
        songNowTime.value = getPlayTime()
      }, 1000)
      songTotleTime.value = getAudioTime()
    })

    ref.addEventListener('error', () => {
      if (currentSongList.value.length == 0) return
      if (!errorTimer) {
        errorTimer = setTimeout(() => {
          ElMessage.error("该歌曲资源不可用,将为您播放下一首!")
          setTimeout(() => {
            nextSong()
          }, 2000);
          errorTimer = null
        }, 200);

      }

    })

  }, {
    once: true
  })
  // 是否静音
  const isMuted = ref(false)

  // 上一首
  const prevSong = () => {
    // 如果是第一个
    if (currentIndex.value == 0) {
      changeSong(baseUrl + currentSongList.value[currentSongList.value.length - 1].url)
    } else {
      currentIndex.value -= 1
      changeSong(baseUrl + currentSongList.value[currentIndex.value].url)
    }
  }
  // 下一首
  const nextSong = () => {
    // 如果是最后一首
    if (currentIndex.value >= currentSongList.value.length - 1) {
      currentIndex.value = 0
      changeSong(baseUrl + currentSongList.value[0].url)
    } else {
      currentIndex.value += 1
      changeSong(baseUrl + currentSongList.value[currentIndex.value].url)
    }
  }
  const toMuted = () => {
    audioRef.value.muted = true
    isMuted.value = true
  }
  const noMuted = () => {
    audioRef.value.muted = false
    isMuted.value = false
  }
  // 静音
  const muted = (target: boolean) => {
    console.log('静音了')
    audioRef.value.muted = target
  }
  //循环播放
  const loopMusic = (target: boolean) => {
    audioRef.value.loop = target
  }
  // 开始播放
  const playMusic = () => {
    audioRef.value.play()
  }
  // 暂停播放
  const stopMusic = () => {
    audioRef.value.pause()
  }
  // 获取音频时长 秒
  const getAudioTime = () => {
    return audioRef.value.duration
  }
  // 获取当前播放时间
  const getPlayTime = () => {
    return audioRef.value.currentTime
  }
  // 设置当前播放时间
  const setPlayTime = (time: number) => {
    audioRef.value.currentTime = time
  }

  // 切换歌曲
  const changeSong = (url: string) => {

    currentSongItem.value = currentSongList.value.find(item => url.endsWith(item.url))
    currentLyric.value = currentSongItem.value.lyric
    currentIndex.value = currentSongList.value.findIndex(item => url.endsWith(item.url))
    audioRef.value.src = url
    audioRef.value.load()
    audioRef.value.play()

  }





  return {
    prevSong,
    nextSong,
    isLoop,
    isMuted,
    toMuted,
    noMuted,
    audioRef,
    isStop,
    showTotalTime,
    showNowTime,
    songTotleTime,
    songNowTime,
    muted,
    loopMusic,
    playMusic,
    stopMusic,
    getAudioTime,
    getPlayTime,
    setPlayTime,
    changeSong,
    currentLyric,
    currentSongList,
    currentSongItem,
    currentIndex,
  }
}
